package cn.leetcode;

import java.util.HashMap;
import java.util.Map;

public class Code560 {
    public static void main(String[] args) {
        int i = subarraySumPro(new int[]{1,-1,0}, 0);
        System.out.println(i);
    }

    public static int subarraySum(int[] nums, int k) {
        int result = 0;
        for(int i=0; i<nums.length; i++){
            int j = i;
            int sum = 0;
            while (j<nums.length){
                sum = sum + nums[j];
                if(sum == k){
                    result++;
                }
                j++;
            }
        }
        return result;
    }


    public static int subarraySumPro(int[] nums, int k) {
        int preSum = 0;
        int result = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int num : nums) {
            preSum = preSum + num;
            int i = preSum - k;
            Integer integer = map.get(i);
            if(integer == null){
                map.merge(preSum, 1, Integer::sum);
            }else {
                Integer count = map.get(preSum);
                if(count == null){
                    count = 1;
                }else {
                    count ++;
                }
                map.put(preSum, count);
                result = result + integer;
            }
        }
        return result;
    }

}
